import information
from utils import *
import threading
from cmd import *
import datetime
from netplug import *
import account

#First impl. : sequential
#FIXME : optimisation des appels (historique ?)

def grabFromContact(ID,author,contactObj,newerThanDate):
    """try to get info (based on ID and authorID) from contactObj with a version newer than newerThanDate
    return infoObj if OK, None otherwise"""
    #if contactObj is current user : we don't need to try...
    if contactObj == account.getMyAccount():
        return None
    #build cmd req for query version date
    cmd = getVerCmd()
    cmd.setID(ID)
    cmd.setAuthorID(author.getID())
    cmd.setSenderID(account.getMyAccount().getID())
    cmd.setSignature(account.getMyAccount().signInformation(cmd))
    #retrieve contact netplugs and loop over it to contact contact
    for param in contactObj.getNetPlugs():
        if param.getType() == NETPLUG_TYPE_TCP:
            netplug = tcpNetPlug(param)
        else:
            warningOutput("netplug type unknown : %s"%(param.getType(),))
            continue
        response = netplug.sendCmd(cmd)
        if (not response) or (response.getType() != CMD_TYPE_RESP) or (response.getCodeRep() != CMD_RESP_CODE_OK):
            continue
        #check response signature
        if not response.checkSignature():
            continue
        #test if newer version
        try:
            responseDate = datetime.datetime.strptime(response.getData(),"%Y-%m-%dT%H:%M:%S.%f")
        except:
            #invalid response to getVer
            continue
        if (not newerThanDate) or (responseDate > newerThanDate):
            #grab the info object from contact
            cmd = getCmd()
            cmd.setID(ID)
            cmd.setAuthorID(author.getID())
            cmd.setSenderID(account.getMyAccount().getID())
            cmd.setSignature(account.getMyAccount().signInformation(cmd))
            response = netplug.sendCmd(cmd)
            #FIXME : improve
            if (not response) or (response.getType() != CMD_TYPE_RESP) or (response.getCodeRep() != CMD_RESP_CODE_OK):
                continue
            #check response signature
            if not response.checkSignature():
                continue
            try:
                infoObj = information.loadInformation(response.getData())
            except:
                continue
            return infoObj
        else:
            return None #we don't try the other netplugs for the same contact, because response will be the same


def mainGrabProcess(ID,author,fr,newerThanDate,callback):
    """main grab algo to get info on the net"""
    infoOutput("Start grabbing info (ID:%s,AuthorID:%s)"%(ID,author.getID()))
    #first try to contact author
    info = grabFromContact(ID,author,author,newerThanDate)
    if info:
        #save to base
        information.setInformation(info)
        #callback if needed
        if callback:
            callback(info)
    else:
        #if failed, try to see if friends have a newer version 
        if fr:
            for friend in fr:
                info = grabFromContact(ID,author,friend,newerThanDate)
                if info:
                    #save to base
                    information.setInformation(info)
                    #callback if needed
                    if callback:
                        callback(info)
                    return #FIXME : what if it exist a newer version ?
        #if nothing found return None to callback
        if callback:
            callback(None)


